<?php

class SupplierStocksOutController extends AppController {

    var $name = 'SupplierStocksOut';
    var $viewPath = 'suppliers/delivery/stocks_out';
    var $pageTitle = 'Inventory out from customer inventory';
    var $uses = array('SSoH', 'SSo', 'CustomerSupplier', 'RunningNo', 'CustProductSite', 'Customer', 'Site', 'Product');
    var $paginate = array(
        'SSoH' => array(
            'order' => 'SSoH.id DESC'
        )
    );

    const SUPPLIER_STOCK_OUT_TYPE = 'VO';

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'supplier_stocks_out');
    }

    function display() {
        parent::display('SSoH');
        $this->paginate['SSoH']['contain'] = array('Customer', 'Site');

        $this->_checkSupplier('SSoH');

        $op = array(
            'stock_out_no' => 'LIKE',
            'stock_out_by' => 'LIKE',
        );

        // มีการ search โดยใช้ stock_out_no ทำให้เป็นพิมพ์ใหญ่
        if (!empty($this->data['SSoH']['stock_out_no'])) {
            $this->data['SSoH']['stock_out_no'] = strtoupper($this->data['SSoH']['stock_out_no']);
        }

        $this->_checkBetweenSearch('SSoH', 'stock_out_date');
        $this->_paging('SSoH', $op);
    }

    function save() {
        $id = null;
        $is_success = true;
        $user_id = $this->Auth->user('id');
        $supplier_id = $this->Auth->user('supplier_id');

        if (!empty($this->data)) {

            // เรียงลำดับรายการใหม่ กรณีลบแถว Outdex เปลี่ยน เรียงตามลำดับที่ป้อนเข้ามา (key)
            $this->adjustRowIndex($this->data['SSo']);

            // ตรวจสอบว่ามีสินค้าอยู่ในใบ SSoH
            if (count($this->data['SSo']) == 0) {
                $this->SeSSoon->setFlash("Stock out must have at least one product !!!.", 'flash/fail');
            } else {
                $this->SSoH->query("BEGIN");

                // Generate Stock out no
                $year = $this->Utility->getThaiYear();
                // Supplier Stock Out Type
                $runno = $this->RunningNo->getNextStockNo(self::SUPPLIER_STOCK_OUT_TYPE, $year);
                $this->Customer->id = $this->data['SSoH']['customer_id'];
                $cust_no = $this->Customer->field('cust_no');
                $this->Site->id = $this->data['SSoH']['site_id'];
                $site_no = $this->Site->field('site_no');
                $this->data['SSoH']['stock_out_no'] = $cust_no . '-' . $site_no . '-' . self::SUPPLIER_STOCK_OUT_TYPE . '-' . $year . $runno;
                $this->data['SSoH']['supplier_id'] = $supplier_id;
                $this->data['SSoH']['user_id'] = $user_id;

                // Save SSoH && SSo
                if ($this->SSoH->saveAll($this->data, array('validate' => 'first', 'atomic' => false))) {
                    // Update Product current stock
                    foreach ($this->data['SSo'] as $SSo) {
                        $cps_id = $SSo['cust_product_site_id'];
                        $this->CustProductSite->id = $cps_id;

                        // ลด current stock ลูกค้าที่คลัง vendor
                        $current_stock = $this->CustProductSite->field('supplier_current_stock') - $SSo['stock_out_qty'];
                        $is_success &= $this->CustProductSite->saveField('supplier_current_stock', $current_stock);

                    }
                } else {
                    $is_success = false;
                }
                if ($is_success) {
                    $this->SSoH->query("COMMIT");
                    $id = $this->SSoH->id;
                    $this->Session->setFlash('Stock out save succesfull.', 'flash/ok');
                } else {
                    $this->SSoH->query("ROLLBACK");
                    $this->Session->setFlash('Stock out save fail!!!.', 'flash/fail');
                }
            }
        }
        $this->data['SSoH']['customer_id'] = null;
        $this->data['SSoH']['site_id'] = null;
        $this->data['SSo'] = null;
        $this->setAction('view', $id);
    }

    function view($id = null) {
        // edit
        if ($id != null) {
            $this->SSoH->contain(array('Customer', 'Site', 'SSo' => array('Product' => array('Unit'), 'CustProductSite')));
            $this->data = $this->SSoH->findById($id);

            $this->_neighbors($id, $this->SSoH, array('fields' => array('id')));
            $this->set('mode', 'edit');
        } else {
            $supplier_id = $this->Auth->user('supplier_id');
            // ดึง list customer ที่มีคลังอยู่ที่ Vendor
            $this->set('customers', $this->CustomerSupplier->listCustomerBySupplierId($supplier_id));
            $this->set('stock_out_by', $this->Auth->user('name')); // กำหนดผู้ทำการ stock out
            $this->set('today', date("d/m/Y"));                 // กำหนด default วันที่ stock out
            $this->set('mode', 'add');
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->SSoH->contain(array('Supplier', 'Customer', 'Site', 'SSo' => array('Product' => array('Unit'), 'CustProductSite')));
        $this->data = $this->SSoH->findById($id);
    }

    function popup_search() {
        parent::popup_search();

        $this->set('customers', $this->CustomerSupplier->listCustomerBySupplierId($this->Auth->user('supplier_id')));
        $this->set('popupWidth', 500);
    }

}

?>
